package com.vue.demo.handler;

import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiaojf
 */
public class StringListTypeHandler extends JacksonTypeHandler {
    private final ObjectMapper objectMapper = new ObjectMapper();

    public StringListTypeHandler(Class<? super Object> type) {
        super(type);
    }

    @Override
    protected Object parse(String json) {
        try {
            return objectMapper.readValue(json, new TypeReference<List<String>>() {

            }).stream().map(s ->s).collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected String toJson(Object obj) {
        if (obj instanceof List) {
            try {
                return objectMapper.writeValueAsString(((List<String>) obj).stream().map(s -> {
                  return s;
                }).collect(Collectors.toList()));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

        }
        return null;
    }
}